package com.white.mybatis.dynamic;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.white.mybatis.dynamic.exceptions.DynamicMapperException;

/**
 * <p>
 * SQL元数据
 * </p>
 *
 * @author huangzy
 * @since 2022/2/25
 */
public final class SqlSource {

    /**
     * 含有占位符 ’?‘ 的sql语句
     */
    private final String sql;

    /**
     * 占位符参数
     */
    private final Object[] params;

    public SqlSource(QueryWrapper<?> wrapper){
        if (wrapper == null) {
            this.sql = "";
            this.params = new Object[0];
            return;
        }
        //获取SQL
        this.sql = wrapper.getTargetSql();
        //获取占位符参数
        this.params = wrapper.getParamNameValuePairs()
                .keySet()
                .stream()
                .sorted((a,b) -> {
                    int aIndex = Integer.parseInt(a.replace(Constants.WRAPPER_PARAM, ""));
                    int bIndex = Integer.parseInt(b.replace(Constants.WRAPPER_PARAM, ""));
                    return aIndex - bIndex;
                })
                .map(key -> wrapper.getParamNameValuePairs().get(key))
                .toArray(Object[]::new);
    }

    public String getSql() {
        if (sql == null || sql.length() == 0) {
            return sql;
        }
        return " WHERE ( " + sql + " ) ";
    }

    public Object[] getParams() {
        return params;
    }
}
